import os
from datetime import timedelta
from flask import Flask, jsonify
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from flask_migrate import Migrate
from config import Config  # 改为相对导入
from database import db, init_db  # 改为相对导入
from routes.device_data import device_data_bp
from routes.dashboard import dashboard_bp
from routes.test_data import test_data_bp
from routes.auth import auth_bp
from routes.employee import employee_bp

def create_app(config_class=Config):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(config_class)

    # 添加请求日志
    @app.before_request
    def log_request_info():
        from flask import request
        print(f"Request: {request.method} {request.path}")
        print(f"Headers: {dict(request.headers)}")
        print(f"Data: {request.data}")

    # Ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # Initialize database and migrations first
    db.init_app(app)
    from flask_migrate import Migrate
    migrate = Migrate(app, db)

    # Initialize other extensions
    CORS(app, resources={r"/*": {"origins": "*"}})

    # 配置JWT
    app.config['JWT_HEADER_TYPE'] = 'Bearer'
    app.config['JWT_HEADER_NAME'] = 'Authorization'
    app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=24)  # 增加令牌过期时间到24小时
    app.config['JWT_BLACKLIST_ENABLED'] = False  # 禁用黑名单
    app.config['JWT_ERROR_MESSAGE_KEY'] = 'message'  # 错误消息键

    jwt = JWTManager(app)

    # JWT error handlers
    @jwt.expired_token_loader
    def expired_token_callback(jwt_header, jwt_payload):
        return jsonify({
            'message': 'The token has expired',
            'error': 'token_expired'
        }), 401

    @jwt.invalid_token_loader
    def invalid_token_callback(error):
        return jsonify({
            'message': 'Signature verification failed',
            'error': 'invalid_token'
        }), 401

    @jwt.unauthorized_loader
    def missing_token_callback(error):
        return jsonify({
            'message': 'Request does not contain an access token',
            'error': 'authorization_required'
        }), 401

    @jwt.needs_fresh_token_loader
    def token_not_fresh_callback(jwt_header, jwt_payload):
        return jsonify({
            'message': 'The token is not fresh',
            'error': 'fresh_token_required'
        }), 401

    @jwt.revoked_token_loader
    def revoked_token_callback(jwt_header, jwt_payload):
        return jsonify({
            'message': 'The token has been revoked',
            'error': 'token_revoked'
        }), 401

    # Import models after db initialization
    with app.app_context():
        from models import User, Role, Permission, Device, DeviceData, ProductionBatch, Department, Employee
        db.create_all()  # Ensure tables exist before migrations

    # Register blueprints
    app.register_blueprint(device_data_bp, url_prefix='/api/device-data')
    app.register_blueprint(dashboard_bp, url_prefix='/api/dashboard')
    app.register_blueprint(test_data_bp, url_prefix='/api/test-data')
    app.register_blueprint(auth_bp, url_prefix='/api/auth')
    app.register_blueprint(employee_bp, url_prefix='/api/employees')

    # Initialize database
    with app.app_context():
        init_db()

    return app

app = create_app()

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
